package controllers

import (
	"fmt"
	"time"

	//"fmt"
	"macapp/models"
	"strconv"
	"strings"
	"unsafe"

	"github.com/astaxie/beego"
)

type AdminCamilleController struct {
	beego.Controller
}

func (a *AdminCamilleController) Index() {
	a.TplName = "admin/camille.html"
}

func (a *AdminCamilleController) GetAll() {
	var camillesjson models.CamilleJson
	var camilles []models.Camille

	page := a.GetString("page")
	limit := a.GetString("limit")
	int_page, _ := strconv.Atoi(page)
	int_limit, _ := strconv.Atoi(limit)

	qs := models.O.QueryTable(new(models.Camille))
	qs.Limit(int_limit, (int_page-1)*int_limit).OrderBy("-id").All(&camilles)

	camillesjson.Code = 0
	camillesjson.Msg = ""
	camillesjson.Count = GetCamilleCounts()
	camillesjson.Data = camilles
	a.Data["json"] = &camillesjson
	a.ServeJSON()

}

func (a *AdminCamilleController) Add() {
	a.TplName = "admin/camille-add.html"
}

func (a *AdminCamilleController) AddApi() {
	var camilles []models.Camille
	numbers := a.GetString("numbers")
	frequency := a.GetString("frequency")
	int_numbers, _ := strconv.Atoi(numbers)
	for i := 0; i <int_numbers ; i++ {
		camille:=new(models.Camille)
		camillesid:=strings.ToUpper(models.GetRandomString(16))
		MD5_UP:=strings.ToUpper(models.Md5(camillesid))

		tmp0:=Substr(MD5_UP,0,5)
		tmp1:=Substr(MD5_UP,5,5)
		tmp2:=Substr(MD5_UP,10,5)
		tmp3:=Substr(MD5_UP,15,5)
		card_number:=tmp0+"-"+tmp1+"-"+tmp2+"-"+tmp3

		camille.Cardid=camillesid
		camille.Cardnumber=card_number
		camille.Amountofdownloads=frequency

		fmt.Println("Add >>> Cardid"+camillesid+"  Cardnumber"+card_number)
		time.Sleep(1)

		camilles=append(camilles,*camille)
	}

	_,err:=models.O.InsertMulti(100, camilles)
	fmt.Println(err)
	a.Ctx.WriteString("success ")
}

//字符串截取
func Substr(str string, start int, length int) string {
	rs := []rune(str)
	rl := len(rs)
	end := 0

	if start < 0 {
		start = rl - 1 + start
	}
	end = start + length

	if start > end {
		start, end = end, start
	}

	if start < 0 {
		start = 0
	}
	if start > rl {
		start = rl
	}
	if end < 0 {
		end = 0
	}
	if end > rl {
		end = rl
	}

	return string(rs[start:end])
}

func GetCamilleCounts() int {
	int64_cnt, _ := models.O.QueryTable(new(models.Camille)).Count()
	//int64 转int
	cnt := *(*int)(unsafe.Pointer(&int64_cnt))
	return cnt
}
